<template>
  <el-card>
    <el-form ref="formRef" :model="skuForm" :rules="rules" label-width="100px">
      <!--
        skuName 名称
        skuDesc 描述
        price 价格
        weight 重量
        tmId 品牌
        skuAttrValueList 平台属性
        skuSaleAttrValueList 销售属性
        skuImageList 图片列表
        skuDefaultImg 默认图片
       -->
      <el-form-item label="SKU名称" prop="skuName">
        <el-input v-model="skuForm.skuName" placeholder="请输入SKU名称" />
      </el-form-item>
      <el-form-item label="SKU描述" prop="skuDesc">
        <el-input
          v-model="skuForm.skuDesc"
          type="textarea"
          :rows="2"
          placeholder="请输入SKU描述"
        />
      </el-form-item>
      <el-form-item label="SKU价格" prop="price">
        <el-input-number
          v-model="skuForm.price"
          controls-position="right"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="SKU重量" prop="weight">
        <el-input-number
          v-model="skuForm.weight"
          controls-position="right"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="SKU品牌" prop="tmId">
        <el-select v-model="skuForm.tmId" placeholder="请选择SKU品牌">
          <el-option
            v-for="tm in trademarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row>
          <el-col
            v-for="(attr, index) in attrList"
            :key="attr.id"
            :xs="24"
            :sm="12"
            :md="8"
          >
            <div>
              <span class="sku-label">{{ attr.attrName }}</span>
              <el-select
                v-model="skuForm.skuAttrValueList[index]"
                placeholder="请选择"
              >
                <el-option
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row>
          <el-col
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
            :xs="24"
            :sm="12"
            :md="8"
          >
            <div>
              <span class="sku-label">{{ saleAttr.saleAttrName }}</span>
              <el-select
                v-model="skuForm.skuSaleAttrValueList[index]"
                placeholder="请选择"
              >
                <el-option
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                  :key="saleAttrValue.id"
                  :label="saleAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="SKU图片" prop="skuImageList">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelectionChange"
        >
          <!--
            type="selection"
            多选框
          -->
          <el-table-column type="selection" width="55" />
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img class="sku-img" :src="row.imgUrl" :alt="row.imgName" />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" />
          <el-table-column label="操作" width="250">
            <template v-slot="{ row }">
              <el-button
                v-if="row.isDefault === 1"
                type="success"
                size="small"
                disabled
              >
                默认图片
              </el-button>
              <el-button
                v-else
                type="primary"
                size="small"
                @click="setSkuDefaultImg(row)"
              >
                设置默认图片
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addSku">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { mapState } from 'vuex'
// import { getSpuImageListById, getSpuSaleAttrListById } from '@/api/product/spu'
// import { getAllTrademarkList } from '@/api/product/trademark'
// import { getAttrList } from '@/api/product/attr'
// import { saveSku } from '@/api/product/sku'

export default {
  name: 'AddSku',
  props: {
    spuId: {
      type: Number,
      required: true
    }
  },
  data() {
    const validator = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请至少选中一张图片'))
        return
      }

      if (!this.skuForm.skuDefaultImg) {
        callback(new Error('请选中一张默认图片'))
        return
      }

      callback()
    }

    return {
      spuImageList: [],
      spuSaleAttrList: [],
      trademarkList: [],
      attrList: [],
      skuForm: {
        skuName: '',
        skuDesc: '',
        price: '',
        weight: '',
        tmId: '',
        skuAttrValueList: [],
        skuSaleAttrValueList: [],
        skuImageList: [],
        skuDefaultImg: ''
      },
      rules: {
        skuName: [
          { required: true, message: '请输入SKU名称', trigger: 'blur' }
        ],
        skuDesc: [
          { required: true, message: '请输入SKU描述', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入SKU价格', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入SKU重量', trigger: 'blur' }],
        tmId: [{ required: true, message: '请选择SKU品牌' }],
        skuAttrValueList: [
          { required: true, type: 'array', message: '请选择SKU平台属性' }
        ],
        skuSaleAttrValueList: [
          { required: true, type: 'array', message: '请选择SKU销售属性' }
        ],
        skuImageList: [
          {
            required: true,
            // type: 'array',
            // message: '请选择SKU图片列表'
            validator
          }
        ]
        // skuDefaultImg: [
        //   { required: true, message: '请选择SKU默认图片', trigger: 'blur' }
        // ]
      }
    }
  },
  computed: {
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id'])
  },
  async mounted() {
    const { spuId, category1Id, category2Id, category3Id } = this

    const promises = [
      // 请求图片列表
      this.$API.product.spu.getSpuImageListById(spuId),
      // 请求销售属性列表
      this.$API.product.spu.getSpuSaleAttrListById(spuId),
      // 请求品牌列表
      this.$API.product.trademark.getAllTrademarkList(),
      // 请求平台属性列表
      this.$API.product.attr.getAttrList({
        category1Id,
        category2Id,
        category3Id
      })
    ]

    const [spuImageListRes, spuSaleAttrListRes, trademarkListRes, attrListRes] =
      await Promise.all(promises)

    this.spuImageList = spuImageListRes.data
    this.spuSaleAttrList = spuSaleAttrListRes.data
    this.trademarkList = trademarkListRes.data
    this.attrList = attrListRes.data
  },
  methods: {
    cancel() {
      this.$emit('setIsShow', 1)
    },
    // 添加sku
    addSku() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          /*
            {
              "category3Id": 0,
              "price": 0,
              "skuAttrValueList": [
                {
                  "attrId": 0,
                  "attrName": "string",
                  "valueId": 0,
                  "valueName": "string"
                }
              ],
              "skuDefaultImg": "string",
              "skuDesc": "string",
              "skuImageList": [
                {
                  "id": 0,
                  "imgName": "string",
                  "imgUrl": "string",
                  "isDefault": "string",
                  "skuId": 0,
                  "spuImgId": 0
                }
              ],
              "skuName": "string",
              "skuSaleAttrValueList": [
                {
                  "saleAttrId": 0,
                  "saleAttrName": "string",
                  "saleAttrValueId": 0,
                  "saleAttrValueName": "string",
                }
              ],
              "spuId": 0,
              "tmId": 0,
              "weight": "string"
            }
          */
          const { category3Id, skuForm, spuId } = this

          await this.$API.product.sku.saveSku({
            category3Id,
            ...skuForm,
            spuId,
            skuAttrValueList: skuForm.skuAttrValueList.map((attr) => {
              const [attrId, attrName, valueId, valueName] = attr.split(':')
              return { attrId, attrName, valueId, valueName }
            }),
            skuSaleAttrValueList: skuForm.skuSaleAttrValueList.map(
              (saleAttr) => {
                const [
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                ] = saleAttr.split(':')
                return {
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                }
              }
            )
          })

          this.$message.success('添加SKU成功')
          this.cancel()
        }
      })
    },
    // 多选框点击的事件，将选中的值作为参数传入
    handleSelectionChange(val) {
      // console.log(val)
      this.skuForm.skuImageList = val
    },
    // 设置默认图片
    setSkuDefaultImg(row) {
      // row.isDefault = 1 // 不是响应式
      // 将所有图片变成不是默认图片
      this.spuImageList.forEach((img) => {
        this.$set(img, 'isDefault', 0)
      })
      // 再将当前点击的变成默认图片
      row.isDefault = 1
      this.skuForm.skuDefaultImg = row.imgUrl
      // 重新校验
      this.$refs.formRef.validateField(['skuImageList'])
    }
  }
}
</script>

<style>
.sku-img {
  width: 150px;
  height: 150px;
}
.sku-label {
  display: inline-block;
  width: 100px;
  text-align: center;
  margin-bottom: 10px;
}
</style>
